package com.demo.mqtt.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

/**
 * @program: mqtt
 * @description:
 * @author: liuYunKai
 * @create: 2021-03-25 10:40
 */
public class HexConvertUtil {
    /**
     * 将十六进制的字符串转换成字节数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStrToByteArrs(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        // toUpperCase将字符串中的所有字符转换为大写
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        // toCharArray将此字符串转换为一个新的字符数组。
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
    //返回匹配字符
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
    /**
     * 数组转换成十六进制字符串
     *
     * @param byte[]
     * @return HexString
     */
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }



    public static void main(String[] args) {

        String string = "C0 10 00 00 00 02 04 00 01 00 00 a2 6f";
        byte[] bs = { -64, 16, 0, 0, 0, 2, 4, 0, 1, 0, 0, -94, 111 };
        System.out.println(Arrays.toString(hexStrToByteArrs(string)));
        System.out.println(bytesToHexString(bs));

        System.out.println(bytesToHexString(hexStrToByteArrs(string)));
    }
}
